/* eslint-disable jsx-a11y/no-noninteractive-element-interactions */
/* eslint-disable no-nested-ternary */
import React, { Fragment } from 'react';
import { Dispatch } from 'redux';
import { connect } from 'dva';

import PageHeader from '@/components/PageHeader';

import {
    Card,
    Table,
    Descriptions,
    Button,
} from 'antd';

import {
    EyeOutlined,
    EyeInvisibleOutlined,
    ZoomOutOutlined,
    ZoomInOutlined,
    CloseCircleOutlined,
    UndoOutlined,
    DownloadOutlined,
} from '@ant-design/icons';

import { watermark } from '@/utils/utils';

import styles from './index.less';

const { Item } = Descriptions;
interface DetailProps {
    dispatch: Dispatch<any>;
    loading: boolean;
    currentUser: any;
    deliveryDetail: any;
    match: { params: { id: number } };
}

interface DetailState {
    showPwd: boolean;
    imgSize: number;
    imgRotate: number;
    rowId: number;
}

const changeWayDict = {
    0: '未收费',
    14101: '支付宝支付',
    14102: '微信支付',
    14103: '余额支付',
    14104: '现金支付',
    14105: "招商银行一网通",
    14106: "甘肃农信APP",

};

@connect(({
    logisCenterDeliveryDetail,
    user: { currentUser },
    loading,
}: any) => ({
    deliveryDetail: logisCenterDeliveryDetail,
    currentUser,
    loading: loading.effects['logisCenterDeliveryDetail/fetch'],
}))

class FranchiseeDetail extends React.Component<DetailProps, DetailState> {
    columns = [
        {
            title: '短信发送时间',
            dataIndex: 'createTime',
            width: 160,
        },
        {
            title: '短信回执时间',
            dataIndex: 'reportTime',
            width: 160,
        },
        {
            title: '接收平台',
            dataIndex: 'dest',
            width: 80,
        },
        {
            title: '手机号',
            dataIndex: 'phone',
            width: 110,
            render: (text: any, record: any, index: number) => {
                return (<div>{record.phone === '10000000000' ? '隐私号码' : text}</div>)
            }
        },
        {
            title: '业务类型',
            dataIndex: 'bizDesc',
            width: 200,
        },
        {
            title: '短信内容',
            dataIndex: 'content',
            width: 450,
        },
        {
            title: '发送状态',
            dataIndex: 'statusDesc',
            width: 80,
        },
        {
            title: '短信通道',
            dataIndex: 'channelDesc',
            width: 80,
        },
        {
            title: '发送平台',
            dataIndex: 'source',
            width: 80,
        },
        {
            title: '发送人',
            dataIndex: 'sender',
            width: 110,
        },
    ];

    columnsWx = [
        {
            title: '推送时间',
            dataIndex: 'time',
            width: 180,
        },
        {
            title: '标题',
            dataIndex: 'title',
            width: 180,
        },
        {
            title: '内容',
            dataIndex: 'desc',
        },
    ];

    columnsThirdWx = [
        {
            title: '推送时间',
            dataIndex: 'time',
            width: 180,
        },
        {
            title: '标题',
            dataIndex: 'title',
            width: 180,
        },
        {
            title: '内容',
            dataIndex: 'desc',
        },
        {
            title: '第三方微信名称',
            dataIndex: 'serviceName',
        },
    ];

    state: DetailState = {
        showPwd: false,
        imgSize: 1,
        imgRotate: 0,
        rowId: 0,
    }

    myRef: any = React.createRef();

    componentDidMount() {
        const {
            match: { params: { id } },
            currentUser,
        } = this.props;
        this.fetchDeliveryDetail(id);

        watermark(this.myRef.current, {
            watermark_txt: `中科富创 ${currentUser?.phone?.substring(7)}`,
        });
    }

    componentDidUpdate(prevProps: DetailProps) {
        const { match: { params: { id } } } = this.props;
        const { match: { params: { id: prevId } } } = prevProps;

        if (prevId !== id) this.fetchDeliveryDetail(id);
    }

    // 点击面单图片
    handleExpress = (e: any, remark: any, id: any) => {
        const divs: any = document.getElementsByClassName('imgContent');
        const div: any = document.getElementById(`imgContent${id}`);

        Array.prototype.forEach.call(divs, (element: any) => {
            element.style.display = 'none';
            const img = element.getElementsByTagName('img')[0];
            img.style.transform = 'scale3d(1,1,1) rotate(0deg)';
        });

        div.style.display = 'block';
        this.setState({ imgSize: 1, imgRotate: 0 });
    }

    // 关闭弹框
    closeImageModel = () => {
        this.setState({ imgSize: 1 });
    }

    // 放大和缩小
    handleChangeImgSize = (size: number, id: any) => {
        const { imgSize, imgRotate } = this.state;
        const middleImageSize = imgSize + size;
        const new_imgSize = middleImageSize < 0.5 ? imgSize : middleImageSize;

        this.commonFun(new_imgSize, imgRotate, id);
    }

    // 旋转
    handleRotating = (id: any) => {
        const { imgSize, imgRotate } = this.state;
        const new_imgRotate = imgRotate - 90;

        this.commonFun(imgSize, new_imgRotate, id);
    }

    // 下载图片
    handleDownImage = (imgSrc: any) => {
        const canvas: any = document.createElement('canvas');
        const img = document.createElement('img');
        img.onload = (e) => {
            canvas.width = img.width;
            canvas.height = img.height;
            const context = canvas.getContext('2d');
            context?.drawImage(img, 0, 0, img.width, img.height);
            canvas.getContext('2d').drawImage(img, 0, 0, img.width, img.height);
            canvas.toBlob((blob: any) => {
                const link = document.createElement('a');
                link.href = window.URL.createObjectURL(blob);
                link.download = '';
                link.click();
            }, 'image/jpeg');
        };
        img.setAttribute('crossOrigin', '*');
        img.src = imgSrc;
    }

    commonFun = (imgSize: any, imgRotate: any, id: any) => {
        const img: any = document.getElementById(`img${id}`);
        img.style.transform = `scale3d(${imgSize},${imgSize},1) rotate(${imgRotate}deg)`;

        this.setState({ imgSize, imgRotate });
    }

    // 关闭
    handleCloseImg = (id: any) => {
        const div: any = document.getElementById(`imgContent${id}`);
        const img: any = document.getElementById(`img${id}`);

        div.style.display = 'none';
        img.style.left = '';
        img.style.top = '';
        img.style.transform = 'scale3d(1,1,1) rotate(0deg)';
        this.setState({ imgSize: 1, imgRotate: 0 });
    }

    // 拖拽图片
    mousedownImage = (e: any, id: any) => {
        const event = e || window.event;
        const target = event.target || event.srcElement;
        const disX = event.clientX - target.offsetLeft;
        const disY = event.clientY - target.offsetTop;
        const p: any = document.getElementById(`imgText${id}`);
        p.style.display = 'none';

        document.onmousemove = (ev: any) => {
            ev.preventDefault();
            const events = ev || window.event;
            const img: any = document.getElementById(`img${id}`);
            const needX = events.clientX - disX;
            const needY = events.clientY - disY;
            img.style.left = `${needX}px`;
            img.style.top = `${needY}px`;
        };

        document.onmouseup = () => {
            document.onmousemove = null;
            document.onmouseup = null;
        };
    }

    onClickRow = ({ id }: any) => ({
        onClick: () => {
            this.setState({ rowId: id });
        },
    })

    setRowClassName = ({ id }: any) => {
        const { rowId } = this.state;
        return id === rowId ? 'clickRowStyl' : '';
    }

    /**
     * 查询详情
     */

    fetchDeliveryDetail(id: number) {
        const { dispatch } = this.props;
        // console.log(dispatch)
        dispatch({
            type: 'logisCenterDeliveryDetail/fetch',
            payload: { id },
        });
    }

    render() {
        const { columns, columnsWx, columnsThirdWx } = this;
        const { showPwd } = this.state;
        const { deliveryDetail, currentUser } = this.props;

        const {
            orderInfo = {},
            operLogInfo = [],
            chargeDetails = {},
            smsInfo = [],
            wechatInfo = [],
            extWechatInfo = [],
        } = deliveryDetail;

        const {
            totalExpectAmount,
            totalPaidAmount,
        } = chargeDetails;

        let {
            delivery = {},
            collect = {},
            pickup = {},
        } = chargeDetails;

        delivery = delivery || {};
        collect = collect || {};
        pickup = pickup || {};

        const pkgNum = !orderInfo.pkgNum || orderInfo.pkgNum === '0' ? '' : ` ${orderInfo.pkgNum}`;
        const pkgText = orderInfo.storageType !== 5 ? pkgNum : '';

        const status_over = [10102, 10104, 10122, 10126, 10128, 10131, 10108];
        const weekArr = ['周日', '周一', '周二', '周三', '周四', '周五', '周六'];

        return (
            <Fragment>
                <PageHeader />

                <div ref={this.myRef}>
                    <Card
                        bordered={false}
                        title="快递详情"
                        className="paddingB10"
                    >
                        <Descriptions bordered size="small">
                            <Item label="运单号">{orderInfo.expCode}</Item>
                            {currentUser.is_root === 1 && (
                                <Item label="订单ID">{orderInfo.id}</Item>
                            )}
                            <Item label="小区校园">{orderInfo.gardenName}</Item>
                            <Item label="物流中心">{orderInfo.logisName || '--'}</Item>
                            <Item label="快递公司">{orderInfo.expressName}</Item>
                            <Item label="收件人手机">{orderInfo.consigneePhone === '10000000000' ? '隐私号码' : orderInfo.consigneePhone} {orderInfo.banDelivery}</Item>
                            <Item label="取件码">
                                {
                                    orderInfo.openCode
                                        ? (
                                            showPwd
                                                ? (
                                                    <span className={styles.justifyContent}>
                                                        {orderInfo.openCode}
                                                        <EyeOutlined
                                                            className={styles.iconStyle}
                                                            onClick={() => this.setState({ showPwd: !showPwd })}
                                                        />
                                                    </span>
                                                )
                                                : (
                                                    <span className={styles.justifyContent}>
                                                        <span className={styles.relative}>
                                                            {[...new Array(6)].fill('*')}
                                                        </span>
                                                        <EyeInvisibleOutlined
                                                            className={styles.iconStyle}
                                                            onClick={() => this.setState({ showPwd: !showPwd })}
                                                        />
                                                    </span>
                                                )
                                        )
                                        : '--'
                                }
                            </Item>
                            <Item label="订单批次">{orderInfo.batchName}</Item>
                            <Item label="接驳人">{orderInfo.transhipUser || '--'}</Item>
                            <Item label="接驳时间">{orderInfo.createTime}</Item>
                            <Item label="入库时间">{orderInfo.inTime || '--'}</Item>
                            <Item label="出库时间">{orderInfo.outTime || '--'}</Item>
                            <Item label="订单状态">{orderInfo.statusName}</Item>
                            <Item label="投递类型">{orderInfo.deliveryWayName}</Item>
                            <Item label="包裹编号">{orderInfo.pkgNum || '--'}</Item>
                            <Item label="到付金额">{(orderInfo.payment || 0) / 100}</Item>
                            <Item label="取件费用">
                                {
                                    orderInfo.status === 10135
                                        ? <span>*</span>
                                        : (
                                            orderInfo.amount && !status_over.includes(orderInfo.status)
                                                ? <span>{(orderInfo.amount || 0) / 100}</span>
                                                : (
                                                    orderInfo.paidAmount !== 0 && status_over.includes(orderInfo.status)
                                                        ? <span>{`${(orderInfo.paidAmount || 0) / 100}/${(orderInfo.expectAmount || 0) / 100}`}</span>
                                                        : <span>{(orderInfo.paidAmount || 0) / 100}</span>
                                                )
                                        )
                                }
                            </Item>
                            <Item label="调价原因">{orderInfo.priceNote || '--'}</Item>
                            <Item label="取件快照">
                                {
                                    orderInfo.pickupImageUrl ? (
                                        <a href={orderInfo.pickupImageUrl} target="blank">
                                            <img
                                                alt=""
                                                style={{ width: 100, height: 100 }}
                                                src={orderInfo.pickupImageUrl}
                                            />
                                        </a>
                                    ) : '无'
                                }
                            </Item>
                            <Item label="投递人姓名">{orderInfo.courierName || '--'}</Item>
                            <Item label="投递人手机">{orderInfo.courierPhone || '--'}</Item>
                            <Item label="存放位置">
                                {
                                    orderInfo.address + pkgText === 'null' || orderInfo.address === null ? '--' : orderInfo.address + pkgText
                                }
                            </Item>
                        </Descriptions>
                    </Card>

                    <Card
                        bordered={false}
                        title="订单操作日志"
                        className="paddingB10"
                        extra={(orderInfo.logisId && (orderInfo.expressId === 8 || orderInfo.expressId === 2)) ? (
                            <span className={styles.hintText}>
                                注意：中通快递、圆通快递派件签收的订单无法对接入库、出库，需要业务员手动签收
                            </span>
                        ) : null}
                    >
                        {(operLogInfo || []).map((log: any) => {
                            const reg = /(https|http|img).+/;
                            const { remark, id } = log;
                            const imgTrue = remark.includes('img:');
                            let remakeContent;

                            if (reg.test(remark)) {
                                remakeContent = (
                                    <div
                                        className="ocrImg"
                                        style={{ flex: 1 }}
                                    >
                                        <span onClick={(e) => this.handleExpress(e, remark, id)}>
                                            {imgTrue ? remark.split('img:')[0] : 'OCR面单图片'}
                                        </span>
                                        <div
                                            id={`imgContent${id}`}
                                            className="imgContent"
                                            style={{
                                                position: 'absolute',
                                                top: '0',
                                                right: '10%',
                                                width: '500px',
                                                height: '600px',
                                                zIndex: 100,
                                                display: 'none',
                                            }}
                                        >
                                            <CloseCircleOutlined
                                                className={styles.closeCircle}
                                                onClick={() => this.handleCloseImg(id)}
                                            />
                                            <div className={styles.checkImg}>
                                                <p className={styles.imgText} id={`imgText${id}`}>图片加载中，请稍后...</p>
                                                <img
                                                    id={`img${id}`}
                                                    className="img"
                                                    src={imgTrue ? remark.split('img:')[1] : remark}
                                                    alt=""
                                                    onMouseDown={(e) => this.mousedownImage(e, id)}
                                                    style={{
                                                        position: 'absolute',
                                                        height: '500px',
                                                        transition: '0.5s',
                                                        zIndex: 101,
                                                        cursor: 'move',
                                                    }}
                                                />
                                            </div>
                                            <div className="marginT20">
                                                <Button
                                                    type="primary"
                                                    icon={<ZoomInOutlined />}
                                                    className="marginR16"
                                                    onClick={() => this.handleChangeImgSize(imgTrue ? 0.5 : 0.2, id)}
                                                >
                                                    放大
                                                </Button>
                                                <Button
                                                    type="primary"
                                                    icon={<ZoomOutOutlined />}
                                                    className="marginR16"
                                                    danger
                                                    onClick={() => this.handleChangeImgSize(imgTrue ? -0.5 : -0.2, id)}
                                                >
                                                    缩小
                                                </Button>
                                                <Button
                                                    type="primary"
                                                    icon={<UndoOutlined />}
                                                    className="marginR16"
                                                    onClick={() => this.handleRotating(id)}
                                                >
                                                    旋转
                                                </Button>
                                                <Button
                                                    type="primary"
                                                    icon={<DownloadOutlined />}
                                                    onClick={() => this.handleDownImage(imgTrue ? remark.split('img:')[1] : remark)}
                                                >
                                                    下载
                                                </Button>
                                            </div>
                                        </div>
                                    </div>
                                );
                            } else {
                                remakeContent = remark;
                            }
                            return (
                                <div
                                    key={log.id}
                                    className="marginB8"
                                    style={{ display: 'flex', lineHeight: '30px', padding: '0 24px' }}
                                >
                                    <span>({weekArr[new Date(log.createTime.split(' ')[0]).getDay()]}) {log.createTime}：
                                    </span>
                                    {remakeContent}
                                </div>
                            );
                        })}
                    </Card>

                    <Card
                        bordered={false}
                        title="收费信息"
                        className="paddingB10"
                    >
                        <Descriptions>
                            <Item label="应收总额">{(Number(totalExpectAmount || 0) / 100)}</Item>
                            <Item label="实收总额">{(Number(totalPaidAmount || 0) / 100)}</Item>
                        </Descriptions>
                        <Descriptions
                            title="投递"
                            className="marginT16"
                        >
                            <Item label="投递应收">{delivery.expectAmount ? (Number(delivery.expectAmount) / 100) : 0}</Item>
                            <Item label="投递实收">{delivery.expectAmount ? (Number(delivery.expectAmount) / 100) : 0}</Item>
                            <Item label="支付方式">{changeWayDict[delivery.chargeWay] || '--'}</Item>
                            <Item label="支付时间">{delivery.chargeTime || '--'}</Item>
                            <Item label="主账户扣费">{delivery.totalMainAmount ? (Number(delivery.totalMainAmount) / 100) : 0}</Item>
                            <Item label="副账户扣费">{delivery.totalDeputyAmount ? (Number(delivery.totalDeputyAmount) / 100) : 0}</Item>
                        </Descriptions>
                        <Descriptions title="到付" className="marginT16">
                            <Item label="到付应收">{collect.expectAmount ? (Number(collect.expectAmount) / 100) : 0}</Item>
                            <Item label="到付实收">{collect.paidAmount ? (Number(collect.paidAmount) / 100) : 0}</Item>
                            <Item label="支付方式">{changeWayDict[collect.chargeWay] || '--'}</Item>
                            <Item label="支付时间">{collect.chargeTime || '--'}</Item>
                        </Descriptions>
                        <Descriptions
                            title="取件"
                            className="marginT16"
                        >
                            <Item label="取件应收">{pickup.expectAmount ? (Number(pickup.expectAmount) / 100) : 0}</Item>
                            <Item label="取件实收">{pickup.paidAmount ? (Number(pickup.paidAmount) / 100) : 0}</Item>
                            <Item label="支付方式">{changeWayDict[pickup.chargeWay] || '--'}</Item>
                            <Item label="支付时间">{pickup.chargeTime || '--'}</Item>
                            <Item label="主账户扣费">{pickup.totalMainAmount ? (Number(pickup.totalMainAmount) / 100) : 0}</Item>
                            <Item label="副账户扣费">{pickup.totalDeputyAmount ? (Number(pickup.totalDeputyAmount) / 100) : 0}</Item>
                        </Descriptions>
                    </Card>

                    <Card bordered={false} title="短信发送详情" className="paddingB10">
                        <Table
                            rowKey="createTime"
                            className="statementTable"
                            columns={columns}
                            dataSource={smsInfo || []}
                            pagination={false}
                            scroll={{ x: 1800 }}
                            onRow={this.onClickRow}
                            rowClassName={this.setRowClassName}
                        />
                    </Card>

                    <Card
                        bordered={false}
                        title="微信推送详情"
                        className="paddingB10"
                    >
                        <Table
                            rowKey="time"
                            className="statementTable"
                            columns={columnsWx}
                            dataSource={wechatInfo || []}
                            pagination={false}
                        />
                    </Card>

                    <Card
                        bordered={false}
                        title="第三方微信推送详情"
                        className="paddingB10"
                    >
                        <Table
                            rowKey="time"
                            className="statementTable"
                            columns={columnsThirdWx}
                            dataSource={extWechatInfo || []}
                            pagination={false}
                        />
                    </Card>
                </div>
            </Fragment>
        );
    }
}

export default FranchiseeDetail;
